""" Build package script. """
import os
import shutil
from localization import DirWalker
import zipfile
import py_compile

ROOT = ".\\..\\"
PACKAGE_ROOT = ROOT + "package\\"
GAME_NAME = "PsyBlockGame"
PACKAGE = PACKAGE_ROOT + GAME_NAME + os.sep

def remove_pyo():
    for path, filename, ext in DirWalker(ROOT, '.pyo'):
        os.remove(ROOT + path + filename)

def mkdir(path):
    try:
        os.makedirs(path)
    except:
        pass

def copy(subpath, *exts):
    root = ROOT + subpath + os.sep

    prevPath = None
    for path, filename, ext in DirWalker(root, *exts):
        if prevPath != path:
            prevPath = path
            print(r'%s\%s' % (subpath, path))

        src = root + path + filename
        dstpath = PACKAGE + subpath + os.sep + path
        mkdir(dstpath)
        shutil.copy(src, dstpath + filename)

def copy_file(name):
    shutil.copy(ROOT + name, PACKAGE + name)

def compile(name):
    for path, filename, ext in DirWalker(ROOT + name, '.py'):
        py_compile.compile(path + filename)

def compress():
    filename = GAME_NAME + '.zip'
    print(GAME_NAME + '.zip')

    zip = zipfile.ZipFile(PACKAGE_ROOT + filename, 'w', zipfile.ZIP_DEFLATED)

    for path, filename, ext in DirWalker(PACKAGE):
        zip.write(PACKAGE + path + filename, GAME_NAME + os.sep + path + filename)

    zip.close()

def main():
    if os.path.isdir(PACKAGE):
        shutil.rmtree(PACKAGE)
    mkdir(PACKAGE)

    compile('src')
    copy('src', '.pyc')
    copy('bin')
    #copy('data')

    copy_file('game.bat')

    compress()

if __name__ == '__main__':
    main()